package com.xiaowu.xblog.filter;


import com.xiaowu.xblog.constant.AuthorizationContext;
import com.xiaowu.xblog.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String path = request.getRequestURI();
        if (path.startsWith("/sysuser")) {
            // 登录/注册相关接口放行，不做 JWT 校验
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            try {
                token = token.replace("Bearer ", "");
                Claims claims = JwtUtil.validateToken(token);

                String username = claims.getSubject();
                Long userId = null;
                Object userIdObj = claims.get("userId");
                if (userIdObj instanceof Integer) {
                    userId = ((Integer) userIdObj).longValue();
                } else if (userIdObj instanceof Long) {
                    userId = (Long) userIdObj;
                }

                if (username != null) {
                    log.info("认证通过，用户: {}，ID: {}", username, userId);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            username, null, null
                    );
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    AuthorizationContext.getContext().setUserId(userId);
                    AuthorizationContext.getContext().setUsername(username);
                    AuthorizationContext.getContext().setToken(token);
                }

            } catch (JwtException e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"error\": \"Invalid JWT token\"}");
                return;
            }
        }

        filterChain.doFilter(request, response);
    }

}
